import ReactDOM from 'react-dom'
const state = []
const setters = []
const effectArray = []
let stateIndex = 0
let effectIndex = 0

const createSetter = index => {
    return function(newValue) {
        state[index] = newValue
        render()
    }
}

const useState = (initState) => {
    if (state[stateIndex] === undefined) state[stateIndex] = initState

    if (!setters[stateIndex]) {
        setters[stateIndex] = createSetter(stateIndex)
    }
    const currentState = state[stateIndex]
    const setter = setters[stateIndex]
    stateIndex++
    return [ currentState, setter]
}

const render = () => {
    stateIndex = 0
    effectIndex = 0
    ReactDOM.render(<EffectComponent />, document.querySelector('#app'))
}

const useEffect = (callback, array) => {
    if (Object.prototype.toString.call(callback) !== '[object Function]') throw new Error('第一个参数必须是函数')
    if (array === undefined) {
        callback()
    } else if (array && Object.prototype.toString.call(array) !== '[object Array]') {
        throw new Error('第二个参数必须是数组')
    } else {
        const preDep = effectArray[effectIndex]
        const hasChanged = preDep ? !array.every((item, index) => preDep[index] === item) : true
        if (hasChanged) callback()
        effectArray[effectIndex] = array
    }
    effectIndex++
}

const EffectComponent = () => {
    const [count, setCount] = useState(0)
    useEffect(() =>  {
        console.log('d111')
    }, [])
    useEffect(() =>  {
        console.log('222')
    }, [count])
    useEffect(() =>  {
        console.log('aaaa')
    })
    return (
        <div>
            <p>{count}</p>
            <button onClick={() => setCount(count + 1)}>+ 1</button>
        </div>
    )
}

export default EffectComponent